package com.linjacy.container.product.aspect;

import com.alibaba.fastjson.JSON;
import com.linjacy.common.utils.PageUtils;
import com.linjacy.container.product.annotation.MyLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

@Component
@Slf4j
@Aspect
public class LogAspect {
    @Pointcut(value = "@annotation(com.linjacy.container.product.annotation.MyLog)")
    public void brokerAspect() {

    }

    @Around(value = "brokerAspect()")
    public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
        long begin = System.currentTimeMillis();
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Method targetMethod = joinPoint.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes());
        MyLog annotation = targetMethod.getAnnotation(MyLog.class);
        String value = annotation.value();
        String level = annotation.logLevel();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = getRemoteHost(request);
        String url = request.getRequestURL().toString();
        String params = Arrays.toString(joinPoint.getArgs());
        log.info("请求源IP:【{}】,请求URL:【{}】,请求参数:【{}】，注解值:【{}】，注解等级:【{}】",  ip,  url, params,value,level);
        Object proceed = joinPoint.proceed();
        long end = System.currentTimeMillis();
        String jsonString = JSON.toJSONString(proceed);
        log.info("返回参数【{}】,执行时间为【{}】毫秒",  jsonString,end-begin);
        return proceed;
    }



    /**
     * 获取目标主机的ip
     *
     * @param request
     * @return
     */
    private String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

}
